<template>
  <div class="Repair">
    <div class="mask"></div>
    <div class="repair">
      <div class="build-top">
        <p>新建（客户返修）</p>
        <i class="el-icon-close" @click="closeRepair"></i>
      </div>
      <div class="build-info">
        <div class="build-info-1">
          <p>客户编号</p>
          <div class="infoBox">
            <el-input v-model="customerNo" @blur="customerNoBlur" :disabled="jxAgent"></el-input>
            <el-select v-model="customerName" @change="e=>{this.customerNo=e}" :disabled="jxAgent">
              <el-option v-for="item in customerList" :key="item.value" :label="item.label" :value="item.value">
                <span style="float:left">{{item.value}}</span>
                <span style="float:right">{{item.label}}</span></el-option>
            </el-select>
          </div>
          <!-- <p>货号</p> -->
          <!-- <el-input v-model="inputSequence"></el-input> -->
          <!-- <el-cascader collapse-tags clearable v-model="kindsNumber" :options="kindsNumberList" :props="props"></el-cascader> -->
          <p>录单日期</p>
          <el-date-picker v-model="inputDate" type="date" value-format="yyyy-MM-dd" placeholder="选择日期"></el-date-picker>
          <p>操作方式</p>
          <el-select v-model="operatingMode" class="_input">
            <el-option v-for="item in operatingModeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
          <p>售价</p>
          <el-input v-model="sellingPrice"></el-input>
        </div>
        <div class="build-info-2">
          <p>备注</p>
          <div class="sty">
            <el-input v-model="remark"></el-input>
          </div>
        </div>
        <div class="build-info-4">
          <el-table id="codeTable" border :data="codeData" class="tb-edit" style="width: 100%;margin-bottom:15px" max-height="148px" @cell-click="cellClick" :header-cell-style="{background:'#f4f4f4',padding:0,height:'40px'}" :cell-style="{padding:0,height:'36px'}">
            <el-table-column :label="header" width="150"></el-table-column>
            <el-table-column prop="colorName" label="颜色" width="100"></el-table-column>
            <template v-for="i in sizeList">
              <el-table-column :prop="i" :label="i" :key="i+Math.random()">
                <template slot-scope="scope">
                  <el-input size="small" class="innerInp" v-model="scope.row[i]" @blur="handleInputBlurResult($event,{index:scope.$index,key:i,result:scope.row[i]})" @keyup.enter.native="inpEnter"></el-input>
                  <!-- <span>{{scope.row[i]}}</span> --></template>
              </el-table-column>
            </template>
          </el-table>
        </div>
        <div class="barcode">
          <p>条码扫描</p>
          <el-switch v-model="isBarcode" active-color="#409EFF" inactive-color="#C0C4CC" :disabled="creating"></el-switch>
        </div>
        <div class="enterBarcode">
          <el-input ref="barcodeInput" @keyup.enter.native="barcodeEnter($event)" v-model="barcode" placeholder="扫描/输入条码，输完按回车"></el-input>
          <span>合计：{{total}}</span>
        </div>
        <el-table height="210px" :data="barcodeData" style="width: 100%" :header-cell-style="{background:'#f4f4f4',padding:0,height:'40px'}" :cell-style="{padding:0,height:'36px'}">
          <el-table-column prop="type" label="类别" width="60"></el-table-column>
          <el-table-column prop="time" label="日期" width="120"></el-table-column>
          <el-table-column prop="customerNo" label="客户编号" width="80"></el-table-column>
          <el-table-column prop="kindsNumber" label="货号" width="180"></el-table-column>
          <el-table-column prop="colorNameSize" label="色码" width="120"></el-table-column>
          <el-table-column prop="sellingPrice" label="售价"></el-table-column>
          <!-- <el-table-column prop="price" label="售价2"></el-table-column> -->
          <el-table-column prop="number" label="数量"></el-table-column>
          <el-table-column prop="remark" label="备注" width="180"></el-table-column>
          <el-table-column prop="operator" label="操作员" width="120"></el-table-column>
          <el-table-column prop="enteringTime" label="录入时间" width="160"></el-table-column>
        </el-table>
      </div>
      <div class="build-btn">
        <div class="btn_f">
          <i class="el-icon-question" style="color:#017aff;margin:5px 6px 0 0;"></i>
          <p>说明：F7 设置扫描数量</p>
        </div>
        <div style="margin:5px 20px 0 0">
          <el-button @click="closeRepair">取消</el-button>
          <el-button @click="saveRepair" type="primary" plain>保存</el-button>
          <el-button @click="continueInput" type="primary">继续录入</el-button></div>
      </div>
    </div>
    <div class="popup" v-show="showPopup">
      <div class="popup_t">
        <p>输入扫描数量</p>
        <i class="el-icon-close" @click="closePopup"></i>
      </div>
      <div class="popup_c">
        <p>请输入扫描数量</p>
        <p>如果不输入则扫描数量为1</p>
        <el-input v-model="scanNum" style="margin-top:10px"></el-input>
        <!-- <input type="text" v-model="scanNum" class="popup_button"> --></div>
      <div class="popup_b">
        <el-button @click="closePopup">取消</el-button>
        <el-button @click="closePopup" type="primary">确定</el-button></div>
    </div>
  </div>
</template>


<script>
import { continueInput, save } from "../../../../network/customerRepair"
import { getKindsNumberList } from '../../../../network/artNo'
import { getBarCode } from '../../../../network/manufacturer'

export default {
  props: {
    sendData: {
      type: Object,
      default: {}
    }
  },
  data(){
    return {
      props: { multiple: true },

      showPopup: false,
      manufacturerBarCode: {},

      customerNo: '',
      customerName: '',
      customerList: [],
      kindsNumber: '',
      kindsNumberList: [],
      inputDate: '',
      operatingMode: '退回',
      operatingModeList: [
        {value:'退回',label:'退回'},
        {value:'归还',label:'归还'},
      ],
      sellingPrice: '',
      remark: '',

      creating: false,
      isBarcode: false,
      barcode: '',
      scanNum: 1,

      header: '',
      sizeList: ['7', '9', '1', '3', '5', '7', 'F'],
      codeData: [],
      barcodeData: [],

      originalData: {},
      jxAgent: document.cookie.match(RegExp('jxAgent'+'=([^;]+)'))[1] == 1 ? true : false,
      total: 0
    }
  },
  watch: {
    show(a,b){
      if (this.creating) this.creating = false
    },
    sendData(a,b){
      this.inputDate = a.inputDate
      this.customerNo = a.customerNo
      this.customerName = a.customerName
      this.customerList = a.customerList
      this.operatingMode = a.operatingMode
      this.sellingPrice = a.sellingPrice
      this.remark = a.remark
    },
    customerNo(a,b){
      this.customerNo = a.toUpperCase().trim()
    },
    barcode(a,b){
      this.barcode = a.toUpperCase().trim()
    }
  },
  methods: {
    sibling(e) {
      let s = []
      let pp = e.parentNode.parentNode.children
      for (let j = 0; j < pp.length; j++) {
        let p = pp[j].children
        for(let i = 0, pl = p.length; i < pl; i++) {
          if(p[i] !== e) s.push(p[i])
        }
      }
      return s
    },
    handleInputBlurResult(e,{index,key,result}) {
      e.target.parentNode.parentNode.parentNode.classList.remove('activeCell')
      // let r = /^\+?[1-9][0-9]*$/
      let r = /^(0|[1-9][0-9]*|-[1-9][0-9]*)$/
      if (result != 0) {
        result = result.replace(/\b(0+)/gi,"")
      }
      if (!r.test(result) && result) {
        this.$alert('数量请输入整数', '', {
          confirmButtonText: '确定'
        })
        this.codeData[index][key] = 0
        return
      }
      this.codeData[index][key] = result
    },
    cellClick(row, column, cell, event){
      cell.classList.add('activeCell')
      let s = this.sibling(cell)
      s.forEach(e => {
        e.classList.remove('activeCell')
      })
    },
    inpEnter(e){
      e.target.parentNode.parentNode.parentNode.classList.remove('activeCell')
    },

    // 扫描
    barcodeEnter(){
      if (this.barcode) {
        if (!this.isBarcode) {
          // 手输款号
          getKindsNumberList({kindsNumberStr: this.barcode}).then(res => {
            if (res.data.data.data.length) {
              this.header = res.data.data.data[0].styleNumber
              this.$emit('inpNumChange')
              this.sellingPrice = res.data.data.data[0].sellingPrice
              // 品牌公司查条码规律详情
              getBarCode({company:res.data.data.data[0].brandedCompany}).then(res => {
                this.manufacturerBarCode = res.data.data[0]
              })
              // console.log(this.manufacturerBarCode)
              // 输入款号显示中间表和尺码信息   ZZZ-AAS
              res.data.data.data.sort((a,b) => {
                return a.relevanceSize.localeCompare(b.relevanceSize)
              })
              let tmp = res.data.data.data
              this.tmpBarcodeData = tmp
              // console.log(tmp)

              // 中间表  尺码表头
              this.sizeList = [tmp[0].size]
              let isExistSize = 0
              for (const i of tmp) {
                for (const j of this.sizeList) {
                  if (j == i.size) {
                    isExistSize = 0
                    break
                  }
                  isExistSize = 1
                }
                if (isExistSize) {
                  this.sizeList.push(i.size)
                }
              }

              // 中间表
              let tmpCodeData = [{colorNo:tmp[0].colorNo,colorName:tmp[0].colorName}]
              let isExistColor = 0
              for (const i of tmp) {
                for (const j of tmpCodeData) {
                  if (j.colorName == i.colorName) {
                    isExistColor = 0
                    break
                  }
                  isExistColor = 1
                }
                if (isExistColor) {
                  tmpCodeData.push({colorNo:i.colorNo,colorName:i.colorName})
                }
              }
              tmpCodeData.forEach(e => {
                this.sizeList.forEach(f => {
                  e[f] = ''
                })
              })
              this.codeData = tmpCodeData
              let codeTable = document.getElementById('codeTable')
              let inputs = codeTable.getElementsByTagName('input')
              // console.log(inputs)
              let int = setInterval(() => {
                clearInterval(int)
                inputs[0].focus()
                inputs[inputs.length - 1].onkeyup = e => {
                  if (window.event.keyCode == 13) {
                    this.continueInput()
                    inputs[inputs.length - 1].onkeyup = () => {}
                  }
                }
              }, 100)
            } else {
              this.$message('此货号/款号无数据')
            }
          })
        } else {
          getKindsNumberList({kindsNumberStr: this.barcode}).then(res => {
            if (res.data.code == 200) {
              this.sellingPrice = res.data.data.data[0].sellingPrice
              this.continueInput()
            }
          })
        }
      }
    },

    // 保存
    saveRepair(){
      if (!this.inputDate) {
        this.$alert('日期不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }
      if (!this.customerNo) {
        this.$alert('客户不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }

      save(JSON.stringify(this.barcodeData)).then(res => {
        console.log(res)
        if (res.data.code == 200) {
          this.$message({
            message: '保存成功,显示数据请按查询',
            type: 'success'
          })
          let send = {
            inputDate : this.inputDate,
            customerNo : this.customerNo,
            customerName : this.customerName,
            operatingMode : this.operatingMode,
            remark : this.remark,
            supList : this.barcodeData
          }
          // 发送到父组件数据
          this.$emit('saveRepair', send)
          this.closeRepair()
        } else {
          this.$message.error('保存失败')
        }
      })
    },

    // 继续录入
    continueInput(){
      if (!this.inputDate) {
        this.$alert('日期不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }
      if (!this.customerNo) {
        this.$alert('客户不能为空', '', {
          confirmButtonText: '确定'
        })
        return
      }

      // 是否有信息变动
      let isNew = false
      
      if (JSON.stringify(this.originalData) == '{}') {
        // 第一次点读卡，记录原始数据
        this.originalData.inputDate = this.inputDate
        this.originalData.customerNo = this.customerNo
        this.originalData.operatingMode = this.operatingMode
        this.originalData.sellingPrice = this.sellingPrice
        this.originalData.remark = this.remark
      } else {
        // 判断是否修改了数据
        for (const key in this.originalData) {
          if (this.originalData.hasOwnProperty(key)) {
            const e = this.originalData[key]
            if (e != this[key]) {
              // 修改了数据 重新赋值
              isNew = true
              this.originalData.inputDate = this.inputDate
              this.originalData.customerNo = this.customerNo
              this.originalData.operatingMode = this.operatingMode
              this.originalData.sellingPrice = this.sellingPrice
              this.originalData.remark = this.remark
              break
            }
          }
        }
      }


      let list = []
      // let kindsNumberNumMap = {}
      if (this.isBarcode) {
        // 扫描
        // kindsNumberNumMap[this.barcode] = this.scanNum
        list[0] = {
          customerNo: this.customerNo,
          kindsNumber: this.barcode,
          number: this.scanNum,
          remark: this.remark,
          repairTime: this.inputDate,
          type: this.operatingMode,
          sellingPrice: this.sellingPrice
        }
      } else {
        // 输入
        let knList = []
        this.codeData.forEach(e => {
          let c = e.colorNo
          this.sizeList.forEach(f => {
            if (this.manufacturerBarCode.styleColorSize) {
              // 型尺色

              if (this.manufacturerBarCode.styleColor) {
                // 款号与尺码之间有 - 

                if (this.manufacturerBarCode.colorSize) {
                  // 色号与尺码之间有 - 
                  knList.push({
                    kindsNumber:`${this.header}-${f}-${c}`,
                    sum:e[f]
                  })
                } else {
                  // 色号与尺码之间没有 -  
                  knList.push({
                    kindsNumber:`${this.header}-${f}${c}`,
                    sum:e[f]
                  })
                }
              } else {
                // 款号与尺码之间没有 - 

                if (this.manufacturerBarCode.colorSize) {
                  // 色号与尺码之间有 -  
                  knList.push({
                    kindsNumber:`${this.header}${f}-${c}`,
                    sum:e[f]
                  }) 
                } else {
                  // 色号与尺码之间没有 - 
                  knList.push({
                    kindsNumber:`${this.header}${f}${c}`,
                    sum:e[f]
                  })
                }
              }
            } else {
              // 型色尺

              if (this.manufacturerBarCode.styleColor) {
                // 款号与颜色之间有 - 

                if (this.manufacturerBarCode.colorSize) {
                  // 色号与尺码之间有 -  
                  knList.push({
                    kindsNumber:`${this.header}-${c}-${f}`,
                    sum:e[f]
                  })
                } else {
                  // 色号与尺码之间没有 -  
                  knList.push({
                    kindsNumber:`${this.header}-${c}${f}`,
                    sum:e[f]
                  })
                }
              } else {
                // 款号与颜色之间没有 - 

                if (this.manufacturerBarCode.colorSize) {
                  // 色号与尺码之间有 -  
                  knList.push({
                    kindsNumber:`${this.header}${c}-${f}`,
                    sum:e[f]
                  })
                } else {
                  // 色号与尺码之间没有 - 
                  knList.push({
                    kindsNumber:`${this.header}${c}${f}`,
                    sum:e[f]
                  }) 
                }
              }
            }
          })
        })
        // console.log(knList)
        for (const i of knList) {
          if (i.sum == '' || i.sum == 0) continue
          list.push({
            customerNo: this.customerNo,
            kindsNumber: i.kindsNumber,
            number: i.sum,
            remark: this.remark,
            repairTime: this.inputDate,
            type: this.operatingMode,
            sellingPrice: this.sellingPrice
          })
          // kindsNumberNumMap[i.kindsNumber] = i.sum
        }
      }

      if (!list.length) {
        this.$alert('无数据无法继续录入', '', {
          confirmButtonText: '确定'
        })
        return
      }
      continueInput(JSON.stringify(list)).then(res => {
        if (res.data.code == 200) {
          this.barcode = ''
          this.header = ''
          this.codeData = []
          this.$refs.barcodeInput.focus()
          if (!this.creating) this.creating = true
          if (res.data.data && res.data.data.length) {
            let isExist = 0
            res.data.data.forEach(e => {
              this.total += Number(e.number)
              e.time = e.repairTime.slice(0,10)
              for (const i of this.barcodeData) {
                if (e.kindsNumber == i.kindsNumber) {
                  i.number += Number(e.number)
                  isExist = 1
                  break
                }
                isExist = 0
              }
              if (!isExist) {
                this.barcodeData.unshift(e)
              }
            })
          }
        }
      })
    },

    closeRepair(){
      this.isBarcode = false
      this.header = ''
      this.codeData = []
      this.barcodeData = []
      this.total = 0
      this.originalData = {}
      this.$emit('closeRepair')
    },

    // F7弹出框
    closePopup(){
      this.showPopup = false
    },

    // 客户编号失去焦点
    customerNoBlur(){
      if (this.customerNo != '') {
        for (const i of this.customerList) {
          if (this.customerNo == i.value) {
            this.customerName = i.label
            return
          }
        }
        this.$alert('无此客户编号', '', {
          confirmButtonText: '确定'
        })
        this.customerNo = ''
        this.customerName = ''
      } else {
        this.customerName = ''
      }
    },
  },
  mounted(){
    let _this = this
    document.onkeydown = function(event){
      let e = event || window.event || arguments.callee.caller.arguments[0]
      if(e && e.keyCode==118){ // 按 F7
      if(_this.showPopup == true){
        _this.showPopup = false
      }else{
        _this.showPopup = true
      }
      }
    }
  }
}
</script>

<style scoped>
  .middle{
    padding: 10px 15px;
  }
  .middle p{
      padding-bottom: 10px;
  }
  ._top{
      display: flex;
      width: 100%;
      height: 40px;
      padding: 10px 15px;
      justify-content: space-between;
      background: #f8f8f8;
      font-weight: 700;
  }
  .scanning{
    width: 400px;
    height: 200px;
    background:white;
    box-shadow: 0 3px 3px 3px #e7e4e4;
    position: abbuildlute;
    top: 30%;
    left: 30%;
    z-index: 1000;
  }
  /* 新建资料 */
  .mask{
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: #000;
    opacity: 0.3;
    z-index: 9;
  }
  .repair{
    position: fixed;
    /* position: relative; */
    top: 7%;
    left: 50%;
    transform: translateX(-50%);
    width: 1020px;
    z-index: 99;
    background-color: white;
    overflow: auto;
  }
  .repair .build-top{
    height: 40px;
    background-color: #f8f8f8;
  }
  .repair .build-top p{
    float: left;
    line-height: 40px;
    padding-left: 20px;
    font-weight: 700;
  }
  .repair .build-top i{
    float: right;
    line-height: 40px;
    padding: 0 16px;
  }

  .repair input{
    height: 30px;
    border: buildlid 1px #DCDFE6;
    border-radius: 5px;
    margin-left: 10px;
  }
  .repair input:focus{
    outline: none;
    border: buildlid 1px #409EFF;
  }
  .repair .build-info-2 .inp-2{
    margin-right: 15px;
  }
  .build-info{
    padding: 0 15px;
    padding-bottom: 10px;
    /* border-bottom: buildlid #f2f2f2 2px; */
  }
  .build-info-1 p,.build-info-2 p{
    display: inline-block;
    width: 75px;
    text-align: right;
    margin-right: 10px;
    line-height: 30px;
  }
  .repair .build-info-2 .sty {
    display: inline-block;
  }
  .repair .build-info-1 .inp-2{
    margin-right: 43px;
  }
  .build-info .build-info-2{
    margin-bottom: 10px;
  }
  .build-info .barcode p{
    display: inline;
    margin-right: 15px;
  }
  .build-info .barcode div{
    margin-top: 15px;
  }
  .barcode{
    margin-top: 15px;
  }

  .barcode-info-1 p, .barcode-info-2 p{
    display: inline-block;
    width: 96px;
    text-align: right;
    margin-right: 9px;
  }
  .barcode-info-1 p:first-child, .barcode-info-2 p:first-child{
    width: 65px;
  }
  .colorBox, .infoBox {
    display: inline;
  }

  .enterBarcode{
    height: 60px;
    background-color: #f2f2f2;
    margin: 15px 0;
  }

  .build-btn{
    /* text-align: right; */
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
  /* .cell{
    height: 40px;
  } */
  .popup{
    width: 400px;
    height: 200px;
    border: 1px solid #dbdbdb;
    box-shadow: 0 2px 2px 2px #dbdbdb;
    z-index: 999;
    position: absolute;
    left: 50%;
    top: 50%;
    margin:-100px 0 0 -200px;
    background: white;
    /* display: block; */
  }
  .popup_t{
    display: flex;
    justify-content: space-between;
    width: 100%;
    height: 40px;
    background: rgb(244, 244, 244);
    padding: 8px 15px;
  }
  .popup_t p{
    font-weight: 700;
  }
  .popup_c{
    padding: 8px 15px;
  }
  .popup_button{
    margin: 5px 0 0 0;
    width: 94%;
    height: 30px;
    padding:0 10px;
    border: 1px solid#dbdbdb;
    border-radius: 3px;
  }
  .popup_b{
    margin: 10px 0 0 0;
    padding-left: 230px;
  }
  .btn_f{
    display: flex;
    margin-left: 30px;
    background: #f4f4f4;
    border-radius: 15px;
    padding: 5px 25px;
  }

</style>

<style>

  .Repair .build-info-1 .el-input, .Repair .build-info-2 .sty .el-input{
    width: 415px;
  }
  .Repair .build-info-1 .el-input, .Repair .build-info-2 .el-input{
    margin-top: 10px;
    width: 160px;
  }
  .Repair .el-input__inner{
    height: 30px!important;
  }
  .Repair .el-input__icon{
    line-height: 30px!important;
  }
  .build-info .barcode .el-switch{
    margin: 0!important;
  }

  .Repair .enterBarcode .el-input{
    width: 480px;
    margin: 14px 17px;
  }

  .colorBox .el-input{
    width: 73px;
    margin-right: 10px;
  }
  .Repair .build-info-1 .infoBox .el-input, .Repair .build-info-2 .infoBox .el-input{
    margin: 0 10px 0 0;
    width: 60px;
  }
  .Repair .build-info-1 .infoBox .el-input--suffix, .Repair .build-info-2 .infoBox .el-input--suffix{
    width: 90px;
  }
  .Repair .colorBox .el-input--suffix{
    width: 108px;
  }
  .Repair .build-info-4 .el-form-item {
    margin-bottom: 0;
}
.Repair .build-info-4 .el-table .cell{
    box-sizing: border-box;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: normal;
    word-break: break-all;
    line-height: 41px;
    padding-right: 10px;
    height: 40px;
}
.Repair .build-info-4 .el-input__inner{
  border: 0px;
}
.Repair .build-info-4 .el-input__inner:focus{
  border: 1px solid #017aff;
}

.Repair .el-cascader .el-input{
  width: 160px;
}
</style>